#ifndef __PLAY_MUSIC_H
#define __PLAY_MUSIC_H

#include <stdio.h>
#include <string.h>
#include "WM8960.h"
#include "stm32f4xx.h"
#include "ff.h"

// 发送数据缓冲区大小,不超过65535
#define WAV_BUFFER_SIZE 30000

// RIFF Chunk
typedef __packed struct
{
	uint32_t ChunkID;	// RIFF段标签:"RIFF"
	uint32_t ChunkSize; // RIFF段数据大小
	uint32_t Format;	// 格式标签: "WAVE" = 0X45564157
} ChunkRIFF;

// fmt Chunk
typedef __packed struct
{
	uint32_t ChunkID;		// FMT段标签 "fmt" = 0X20746D66
	uint32_t ChunkSize;		// FMT段块大小(除了ID和Size): 20.
	uint16_t AudioFormat;	// 音频格式 = 0X01,Linear PCM; 0X11,IMA ADPCM
	uint16_t NumOfChannels; // 通道数 1,mono channel; 2,double channel;
	uint32_t SampleRate;	// 采样率;0X1F40,8Khz
	uint32_t ByteRate;		// 字节采样率;
	uint16_t BlockAlign;	// 对齐数 (byte);
	uint16_t BitsPerSample; // 单次采样位数; 4 bits is ADPCM,set as 4
	uint16_t ByteExtraData; // 扩展数据位 ; 2 ;线性PCM格式未使用
} ChunkFMT;

// fact Chunk
typedef __packed struct
{
	uint32_t ChunkID;	// FACT段标签: "fact",0X74636166;线性PCM格式未使用
	uint32_t ChunkSize; // FACT段块大小(除了ID和Size);This is 4.
	uint32_t FactSize;	// Transform to PCM File's size;
} ChunkFACT;

// WAV 文件播放控制块
typedef __packed struct
{
	uint16_t audioformat; // 音频格式；0X01为线性PCM；0X11是IMA ADPCM.
	uint16_t nchannels;	  // track number; 1,single track; 2,dual track;
	uint16_t blockalign;  // 块对齐 (byte);
	uint32_t datasize;	  // wav数据大小;
	uint32_t totsec;	  // 播放时间;
	uint32_t cursec;	  // 当前播放时间 (s)
	uint32_t bitrate;	  // 比特率(bit speed)
	uint32_t samplerate;  // 采样率
	uint16_t bps;		  // 位数，例如: 16bit,24bit,32bit
	uint32_t datastart;	  // 文件中的偏移量
} wavctrl;

// Data Chunk
typedef __packed struct
{
	uint32_t ChunkID;	// DATA段标签: "data" = 0X5453494C
	uint32_t ChunkSize; // 块大小(除了ID和Size)
} ChunkDATA;

// I2S DMA传输回调标志
typedef enum
{
	I2S_No_CallBack = 0,
	I2S_Half_Callback = 1,
	I2S_Callback = 2
} I2S_CallBack_Flag;

extern uint32_t WAV_LastData;
extern uint8_t WAV_Buffer[];

extern uint8_t Play_Flag;
extern uint8_t Pause_Flag;
extern uint8_t End_Flag;
extern I2S_CallBack_Flag volatile I2S_Flag;

extern uint8_t Music_Num_MAX; // 最大的音乐序号
extern int8_t Music_Num;  // 当前播放的音乐序号

FRESULT ScanWavefiles(char *path);
uint8_t Get_WAV_Message(char *fname, wavctrl *wavx);
uint32_t Fill_WAV_Buffer(uint8_t *BUFF, uint16_t size);
uint8_t PlayWaveFile(void);

#endif // __PLAY_MUSIC_H